/*
 * RC4.js
 * Uses Rivest Cipher 4 (ARC4) as a PRNG
 * Copyright (C) Jorge H. C. Lucema.
 */

var RC4 = (function () {

//    "use strict";
    /**
     * Initialize arcfour context from key, an array of ints, each from [0..255]
     * @returns {Arcfour}
     */
    var RC4 = function () {
        this.i = 0;
        this.j = 0;
        this.S = [];
    };

    RC4.init = function (key) {
        var i, j, t;
        for (i = 0; i < 256; ++i) {
            this.S[i] = i;
        }
        j = 0;
        for (i = 0; i < 256; ++i) {
            j = (j + this.S[i] + key[i % key.length]) & 255;
            t = this.S[i];
            this.S[i] = this.S[j];
            this.S[j] = t;
        }
        this.i = 0;
        this.j = 0;
    };

    RC4.next = function () {
        var t;
        this.i = (this.i + 1) & 255;
        this.j = (this.j + this.S[this.i]) & 255;
        t = this.S[this.i];
        this.S[this.i] = this.S[this.j];
        this.S[this.j] = t;
        return this.S[(t + this.S[this.i]) & 255];
    };

    RC4.prototype.init = RC4.init;
    RC4.prototype.next = RC4.next;

    return RC4;
}());
